<template>
  <div class="h-full">
    <el-form ref="tableHeadForm" class="w-4/5 mx-auto mt-12" label-width="120px" :model="configForm">
      <el-form-item :label="translateTitle('Dams.HSM.EXCEL工作表')">
        <div>{{ tableConfig.fileName }}</div>
      </el-form-item>
      <el-form-item :label="translateTitle('Dams.HSM.必填项设置')">
        <span>{{ `${translateTitle('Dams.HSM.设置必填项与EXCEL数据的对应关系')}，${translateTitle('Dams.HSM.关联项需与用户资料处一致')}` }}</span>
      </el-form-item>
      <div class="flex flex-wrap">
        <el-form-item
          v-for="(item, index) in configForm.formItem"
          :key="index"
          class="form-item"
          :label="item.title + ':'"
          :prop="'formItem.' + index + '.value'"
          :rules="{ required: true, message: translateTitle('Dams.HSM.请选择') + item.title, trigger: 'change' }"
        >
          <el-select v-model="item.value" :placeholder="translateTitle('Dams.HSM.请选择') + item.title" @change="selectChange($event, index)">
            <el-option
              v-for="(opItem, opIndex) in selectionList"
              :key="opIndex"
              :disabled="opItem.disabled"
              :label="opItem.label || ' '"
              :value="opItem.value"
            />
          </el-select>
        </el-form-item>
      </div>
      <div class="flex justify-center">
        <el-button size="large" type="primary" @click="back">{{ translateTitle('Dams.HSM.重新上传') }}</el-button>
        <el-button size="large" type="primary" @click="nextStep">{{ translateTitle('Dams.HSM.下一步') }}</el-button>
      </div>
    </el-form>
    <div class="w90 mx-auto mt-8">
      <div v-show="hasImported">
        {{ translateTitle('Dams.HSM.本次导入数量') }}:
        <span class="base-color">{{ gridOptions.data.length }}</span>
        {{ translateTitle('Dams.HSM.条') }}
      </div>
    </div>
    <div class="w90 mx-auto mt-8 table-box">
      <vxe-grid ref="vxeTable" v-bind="gridOptions" />
    </div>
  </div>
</template>
<script>
  let tableHeadId = 0
  import { translateTitle } from '@/utils/i18n'
  import { getStorage, setStorage } from '@/utils/tools'
  import { getList } from '@/project/dams/api/home'
  import { GFCD } from '@/utils/utils'
  import _ from 'lodash'
  export default {
    name: 'Step2',
    emits: ['changeActive'],
    data() {
      return {
        configSetting: GFCD('hsm'),
        // 需要下拉选择的表单项
        configForm: {
          formItem: [
            {
              name: 'user_name',
              title: translateTitle('Dams.HSM.姓名'),
              value: '',
            },
            {
              name: 'phone',
              title: translateTitle('Dams.HSM.手机号'),
              value: '',
            },
            {
              name: 'user_no',
              title: translateTitle('Dams.HSM.工号'),
              value: '',
            },
            {
              name: 'actual',
              title: translateTitle('Dams.HSM.实发薪资'),
              value: '',
            },
            {
              name: 'shouldBe',
              title: translateTitle('Dams.HSM.应发薪资'),
              value: '',
            },
            {
              name: 'standard',
              title: translateTitle('Dams.HSM.岗位标准工资'),
              value: '',
            },
          ],
        },
        // 根据表头生成的下拉选择项
        selectionList: [],
        excelData: getStorage('excelData') || [],
        // 表格的配置数据
        tableConfig: getStorage('tableConfig') || {},
        // 是否已经导入
        hasImported: true,
        gridOptions: {
          border: true,
          stripe: true,
          align: 'center',
          columns: [],
          data: [],
        },
        // 树状表头信息
        treeInfo: [],
        // 重新上传时的表头信息
        updateHeader: [],
      }
    },
    mounted() {
      if (this.excelData && !this.excelData.head) {
        this.excelData = {
          head: this.excelData.splice(0, this.tableConfig.number - 1),
          body: this.excelData,
        }
      }
      setStorage('excelData', this.excelData)
      // 重新上传时获取表头
      if (getStorage('pageType')) {
        this.getOldHeaderInfo()
      } else {
        this.init()
      }
    },
    methods: {
      translateTitle,
      init() {
        this.formatSelectionList()
        this.excelData.head.forEach((item, index) => {
          this.transTableHead(item, index == this.excelData.head.length - 1)
        })
        this.formatTree()
      },
      selectDisable() {
        let resultList = _.map(
            _.filter(this.configForm.formItem, (item) => item.value),
            'value'
          ),
          arr = this.selectionList
        arr.forEach((item) => {
          if (resultList.includes(item.value)) {
            item.disabled = true
          } else {
            item.disabled = false
          }
        })
      },
      // 选择后将表头中的与选中项目对应的项的titile替换为当前下拉框的title
      selectChange(e, index) {
        let item = this.configForm.formItem[index]
        this.selectDisable()
        // 获取要替换的表头信息
        this.tableTitleChange(this.gridOptions.columns, Number(item.value), item.title)
        setStorage('treeInfo', this.gridOptions.columns)
        this.$refs.vxeTable.updateData()
      },
      tableTitleChange(arr, id, title) {
        for (let i = 0; i < arr.length; i++) {
          const elem = arr[i]
          if (elem.field === id) {
            elem.title = title
            break
          } else if (elem.children.length) {
            this.tableTitleChange(elem.children, id, title)
          }
        }
      },
      // 重新上传时,获取头部信息
      async getOldHeaderInfo() {
        let data = {
          salary_type: this.tableConfig.salaryType,
          month: this.tableConfig.month,
          '#LIMIT#': 1,
          '#PAGE_SIZE#': 1000,
        }
        let method = 'hsm.excel.salary.header.query'
        let res = await getList(`${this.configSetting.domain}${this.configSetting.baseUrl}`, {
          method: method,
          data: JSON.stringify(data),
        })
        this.updateHeader = res.data['hsm.excel.salary.header.query'].data
        if (this.updateHeader.length) {
          this.updateHeader.forEach((item) => {
            this.selectionList.push({
              label: item.TITLE,
              value: item.ID,
              width: '200px',
              disabled: false,
            })
          })
          let newHeader = this.toTree(this.updateHeader, '')
          this.gridOptions.columns = this.sortTree(newHeader)
          this.gridOptions.data = this.excelData.body
          setStorage('treeInfo', newHeader)
        } else {
          this.init()
        }
      },
      // 为树状进行排序
      sortTree(arr) {
        function loop(list) {
          return list.sort((n1, n2) => {
            if (n1.children && n1.children.length) {
              n1.children = loop(n1.children)
            }
            return Number(n1.id) - Number(n2.id)
          })
        }
        return loop(arr)
      },
      // 重新上传时生成树状表头
      toTree(arr, parentId) {
        function loop(parId) {
          return arr.reduce((acc, cur) => {
            if (cur.PID === parId) {
              cur.title = cur.TITLE
              cur.id = cur.ID
              cur.pid = cur.PID
              cur.field = cur.id
              cur.checked = true
              cur.children = loop(cur.ID)
              acc.push(cur)
            }
            return acc
          }, [])
        }
        return loop(parentId)
      },
      // 生成表头下拉选项
      formatSelectionList() {
        let list = this.excelData.head[this.excelData.head.length - 1]
        let arr = Object.keys(list)
        arr.forEach((item) => {
          this.selectionList.push({
            label: list[item],
            value: item,
            disabled: false,
          })
        })
      },
      /**
       * 将每行表头去重,并统计重复次数(重复是因为多个重复项表示一个合并的单元格)
       * @param {*} headData 单行表头数据
       */
      transTableHead(headData, isLast) {
        let arr = Object.values(headData)
        let result = [],
          i = 0
        result[i] = [{ title: arr[0], field: 0 }]
        // 统计每行表头重复情况
        arr.reduce(function (prev, cur, index) {
          cur === prev ? result[i].push({ title: cur, field: index }) : (result[++i] = [{ title: cur, field: index }])
          return cur
        })
        // 将结果优化并暂存入数组
        let branches = []
        let index = 0
        result.forEach((item) => {
          branches.push({
            title: item[0].title,
            childNum: item.length, // 重复的次数(也就是单元格所占的格数)
            children: [],
            field: isLast ? item[0].field : null,
            id: tableHeadId,
            checked: true,
            index: index,
            minWidth: '120px',
          })
          tableHeadId++
        })
        this.treeInfo.push(branches)
      },
      /**
       * 将已统计好的结果继续优化为树状结构
       * 这里是从树枝开始向树干存值
       */
      formatTree() {
        let tree = this.treeInfo
        for (let i = tree.length - 1; 0 < i; i--) {
          let cur = tree[i]
          let prev = tree[i - 1]
          prev.forEach((item) => {
            let count = 0
            let j = 0
            // 计算出单元格占用相匹配的表格,再切掉放进父级
            for (j = 0; j < cur.length; j++) {
              let ele = cur[j]
              if (count < item.childNum) {
                count += ele.childNum
              } else {
                break
              }
            }
            let arr = cur.splice(0, j)
            arr.forEach((itemIn) => {
              itemIn.pid = item.id
            })
            item.children.push(...arr)
          })
        }
        this.gridOptions.columns = tree[0]
        this.gridOptions.data = this.excelData.body
        setStorage('treeInfo', tree[0])
        // console.log('-----格式化后的表头-----', tree[0])
      },
      back() {
        this.$emit('changeActive', 1)
      },
      nextStep() {
        this.$refs.tableHeadForm.validate((valid) => {
          if (valid) {
            let headerMap = {}
            this.configForm.formItem.forEach((item) => {
              headerMap[item.name] = Number(item.value)
            })
            this.tableConfig.headerMap = headerMap
            setStorage('tableConfig', this.tableConfig)
            this.$emit('changeActive', 3)
          } else {
            this.$message({
              type: 'error',
              message: translateTitle('Dams.HSM.请检查是否填写完所有项目'),
            })
          }
        })
      },
    },
  }
</script>
<style lang="scss" scoped>
  .base-color {
    color: #6ab8b8;
  }
  .step-box {
    padding-top: 60px;
    .step-icon {
      font-size: 20px;
    }
  }
  .w90 {
    width: 90%;
  }
  .form-item {
    width: 33.3%;
    font-weight: bold;
  }
  .table-box {
    padding-bottom: 40px;
  }
  .form-item {
    :deep(.el-date-editor) {
      width: var(--el-date-editor-width);
    }
  }
  .el-form-item--small.el-form-item {
    width: 50%;
    margin-bottom: 18px;
  }
</style>
